<template>
  <div class="content">
    <jc-button
      :btn-arr="['reload', 'pass', 'sub', 'push', 'option', 'settle', 'batchFill', !list.length && 'check']"
      :disab-arr="['close', 'cancel', 'using', 'com1', 'com2', 'freeze']"
      :fbillno="fbillno"
      url="tSubPpbom/querySubppbomList"
      @submit="submit(1)"
      @noSubmit="submit(2)"
      @audit="audit(1)"
      @pushDown="pushDown"
      @refresh="handleGetUntreated"
      @toExcel="handleExport"
      @settle="settle"
      @check="check('up')"
      @check1="check('down')"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        sortable
        table-selection
        :get-summaries="getSummaries"
        show-summary
        @selectionChange="handleSelectAll"
        @clickRow="detailPurchase"
      >
        <!--销售订单号-->
        <template v-slot:btnStates="col">
          <el-link type="primary" @click="detailPurchase(col.scope.row)">{{ col.scope.row.fbillNo }}</el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:orderSlot="col">
          <el-link type="primary" @click="jumpMateriel(col.scope.row)">
            {{ col.scope.row.fnumber }}
          </el-link>
        </template>
        <!--    物料编码    -->
        <template v-slot:text2Slot="col">
          <el-link type="primary" @click="jumpMateriel1(col.scope.row.faterNumber)">
            {{ col.scope.row.faterNumber }}
          </el-link>
        </template>
        <!--禁用状态-->
        <template v-slot:tagSlot="col">
          <el-tag v-if="col.scope.row.fcloseStatus==='A'">{{ $t('market.no') }}</el-tag>
          <el-tag v-else type="danger">{{ $t('market.yes') }}</el-tag>
        </template>
        <!--审核状态-->
        <template v-slot:btnState="col">
          <span v-if="col.scope.row.fdocumentStatus === ''" />
          <el-tag v-else :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentStatus }}</el-tag>
        </template>
      </jc-table>
      <cardTab @search="handleQueryBomList" />
    </div>
    <!--    分页器-->
    <div class="footer">
      <jc-pagination
        :total="total"
        :page.sync="currentPage"
        :limit.sync="size"
        @pagination="handleGetUntreated"
      />
    </div>
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      top="5vh"
      center
      append-to-body
    >
      <div style="text-align: left;height: 100px;line-height: 100px">
        <el-radio-group v-model="orderLX">
          <el-radio v-for="item in outReceipts" :key="item" :label="item">{{ item }}</el-radio>
        </el-radio-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <upDown v-if="upDownVis" :msg="cha" :fentryid="fentryData" @client="upDownVis=false" />
  </div>
</template>

<script>
import {
  querySubppbomList,
  submitSubPpboms,
  unsubmitSubPpboms,
  auditSubPpboms,
  unauditSubPpboms,
  pushToSubPickmtrl,
  pushToSubReturnmtrl,
  pushToSubUninstock,
  finishSubPpboms, pushToSubSupplement
} from '@/api/production/productionList'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { toMxAmina, Forbiders } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import jcButton from '@/components/Button'

export default {
  name: 'OutsourceList',
  components: {
    cardTab: () => import('@/components/cardTab'),
    upDown: () => import('@/components/upDown'),
    search,
    jcButton,
    filtration
  },
  mixins: [searData],
  props: {
    list: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      upDownVis: false,
      cha: '',
      fentryData: [],
      ftype: 31,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      fbillno: '',
      orderLX: this.$t('menu.outOrder'),
      isdanjuDialog: false,
      outReceipts: [this.$t('menu.outOrder'), this.$t('menu.outSuppLian'), this.$t('menu.outSupplementary')], // 委外 '委外领料单''委外退料单''委外补料单'
      deleteData: [], // 删除用料单数据
      // 表头
      tableData: [], // 销售数据
      tableHeader: [
        { label: this.$t('market.billNo'), type: 'states', prop: 'fbillNo', width: '150px' },
        { label: this.$t('market.state'), type: 'state', prop: 'fdocumentStatus', width: '80' },
        { label: this.$t('market.outstates'), prop: 'fstatus', width: '120px' },
        { label: this.$t('market.paezText1'), prop: 'sal_khddh', width: '120' },
        { label: this.$t('market.productmodel1'), prop: 'fproductmodel', width: '110' },
        { label: this.$t('market.productName'), prop: 'fatername', width: '130' },
        { label: this.$t('market.productNo'), type: 'text2', prop: 'faterNumber', width: '105' },
        { label: this.$t('market.productmodel'), prop: 'faterModel', width: '110px' },
        { label: this.$t('market.subitemNum'), type: 'order', prop: 'fnumber', width: '105' },
        { label: this.$t('market.subitemName'), prop: 'zitemname', width: '120' },
        { label: this.$t('market.fmodel1'), prop: 'zitemxh', minWidth: '120px' },
        { label: this.$t('market.specifica1'), prop: 'zitemgg', minWidth: '130px' },
        { label: this.$t('market.molecule'), prop: 'fnumerator', align: 'right', width: '80' },
        { label: this.$t('market.funit'), prop: 'funitName', width: '80' },
        { label: this.$t('market.mustqty'), prop: 'fmustQty', align: 'right', width: '80px' },
        { label: this.$t('market.pickedQty'), prop: 'fneedQty', align: 'right', width: '80px' },
        { label: this.$t('market.outbillNo'), prop: 'fmobillNo', width: '130px' },
        { label: this.$t('market.outmaterSeq'), prop: 'fmoentrySeq', width: '120' }
      ],
      tableHeader1: [
        { label: this.$t('market.creator'), prop: 'fcreator', width: '100' },
        { label: this.$t('market.createDate'), prop: 'fcreatedate', width: '100' },
        { label: this.$t('market.approver'), prop: 'fapprover', width: '100' },
        { label: this.$t('market.approveDate'), prop: 'fapprovedate', width: '100' }
      ]
    }
  },
  created() {
    this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader.concat(this.tableHeader1)
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '委外用料单列表')
        } else {
          querySubppbomList({
            pageSize: 5000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.list.map(item => {
                return (toMxAmina(item), Forbiders(item))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '委外用料单列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 获取生产列表数据
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        list: this.list,
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details)
      }
      const RES = await querySubppbomList(DATA)
      if (RES.code === 0) {
        this.loading = false
        this.tableData = RES.data.list.map(item => {
          return toMxAmina(item)
        })
        this.total = RES.data.total
      } else {
        this.loading = false
        this.$confirm(RES.message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        })
      }
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 成品 原材料
    handleQueryBomList(ev) {
      this.searCollData = []
      this.currentPage = 1
      this.searCollData = ev
      this.searchSon = ev
      this.handleGetUntreated()
    },
    // 详情
    detailPurchase(ev) {
      const id = ev.fbillNo
      this.$router.push({ path: `/productionOutEdit/${id}` })
    },
    // 全选
    handleSelectAll(val) {
      this.selectVal = []
      this.fentryData = []
      this.fidsData = []
      this.fbillno = val[0].fbillNo
      this.val = val
      val.forEach(item => {
        item.fbillNo && this.selectVal.push(item.fbillNo)
        this.fentryData.push(item.fentryId)
        this.fidsData.push(item.fid)
      })
      this.fidsData = Array.from(new Set(this.fidsData))
    },
    // 下推
    pushDown() {
      this.fmoData = []
      this.fmoentryData = []
      this.fentryData = []
      this.fidsData = []
      if (!this.val) {
        this.$message.error('请选择数据!')
        return
      } else {
        for (const item in this.val) {
          if (this.val[0].lierId !== this.val[item].lierId) {
            this.$message.warning('委外订单下推,供应商必须相同!')
            return
          }
        }
        this.val.forEach(res => {
          this.fentryData.push(res.fentryId)
          this.fidsData.push(res.fid)
          this.fmoData.push(res.fmoId)
          this.fmoentryData.push(res.fmoentryId)
        })
        this.fidsData = Array.from(new Set(this.fidsData))
        this.fmoData = Array.from(new Set(this.fmoData))
        this.fmoentryData = Array.from(new Set(this.fmoentryData))
        this.isdanjuDialog = true
      }
    },
    // 下推
    pushDownOrder() {
      if (this.orderLX === this.$t('menu.outOrder')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData
        }
        pushToSubPickmtrl(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/outOrder/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.outSuppLian')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData
        }
        pushToSubReturnmtrl(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/outSuppleDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.outSupplementary')) {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData
        }
        pushToSubSupplement(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/outSupplementaryEdit/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === '委外退库单') {
        const DATA = {
          SoucrceIds: this.fmoData,
          EntryIds: this.fmoentryData
        }
        pushToSubUninstock(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/outTuiStockDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      }
    },

    // 公共函数
    toExamineFun(api) {
      const DATA = {
        Numbers: this.selectVal,
        fIds: this.fidsData,
        EntryIds: this.fentryData
      }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    async submit(ev) {
      const api = ev === 1 ? submitSubPpboms : unsubmitSubPpboms
      this.toExamineFun(api)
    },
    // 审核
    async audit(ev) {
      const api = ev === 1 ? auditSubPpboms : unauditSubPpboms
      this.toExamineFun(api)
    },
    // 上查、下查
    check(ev) {
      if (this.fentryData.length === 0) return
      this.cha = ev
      this.upDownVis = true
    },
    settle() {
      const api = finishSubPpboms
      this.toExamineFun(api)
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;
  .header{
    position:relative;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px!important;
    }
  }
}
</style>
